//
//  earningsMXViewController.m
//  gpos_app
//
//  Created by apple on 2018/10/16.
//  Copyright © 2018年 apple. All rights reserved.
//

#import "earningsMXViewController.h"
#import "Masonry.h"
#import "GPosAPI.h"
#import "SVProgressHUD.h"
#import "WKProgressHUD.h"
#import "XMRegisterViewController.h"
#import "earningsViewCell.h"
#import "DateTimePickerView.h"
#import "PopupView.h"
#import "MJRefresh.h"
#import "storageModel.h"


@interface earningsMXViewController ()<UITableViewDelegate,UITableViewDataSource,DateTimePickerViewDelegate>
@property (nonatomic,strong)UIButton  * leftButton;
@property (nonatomic,strong)UIButton * rightButton;
@property (nonatomic,strong)UITableView * tableView;
@property (nonatomic,strong)WKProgressHUD * hud;
@property (nonatomic,assign)NSInteger shouYiType;
@property (nonatomic,assign)NSInteger pageSize;
@property (nonatomic,assign)NSInteger pageNum;
@property (nonatomic,strong)NSString * timeStr;
@property (nonatomic,strong)NSMutableArray *modelArr;
@property (nonatomic, strong) DateTimePickerView *datePickerView;


@end

@implementation earningsMXViewController


//改变状态栏
-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    
}
-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithRed:244/255.0f green:244/255.0f blue:244/255.0f alpha:1];
    self.navigationController.navigationBar.hidden = NO;
    //去掉返回的文字
    self.navigationController.navigationBar.topItem.title = @"";
    self.navigationController.navigationBar.backgroundColor=[UIColor whiteColor];
    self.navigationController.navigationBar.tintColor=[UIColor blackColor];
    self.title = @"收益明细";
    
    self.shouYiType = 0;
    self.timeStr = @"";
    [self loadData];
}

- (void)loadData{
    __weak typeof(self) weakSelf = self;
    self.pageNum = 1;
    self.pageSize = 5;
    self.modelArr = [[NSMutableArray alloc] init];
    int user = [[[NSUserDefaults standardUserDefaults] objectForKey:@"userId"] intValue];
    NSDictionary * params = @{@"pageNum" : @(self.pageNum),
                              @"pageSize" : @(self.pageSize),
                              @"type" : @(self.shouYiType),
                              @"time" : self.timeStr,
                              @"userId" : @(user),
                              
                              };
    NSLog(@"oj---%@",params);
    [GPosAPI requestViewIncomeOrderListWithParams:params andCallback:^(id obj) {
        NSLog(@"储存列表---%@",obj);
        
        if (obj==nil) {
            weakSelf.hud=[WKProgressHUD popMessage:@"请求失败" inView:self.view duration:1 animated:YES];
        }else{
            
            if ([[obj objectForKey:@"code"] intValue] == 200) {
                NSArray * arr = [[NSArray alloc] init];
                arr = [obj objectForKey:@"data"];
                for (NSDictionary * dic in arr) {
                    storageModel *model = [[storageModel alloc] init];
                    NSDecimalNumber * number = [dic objectForKey:@"amount"];
                    model.amount = [NSString stringWithFormat:@"%@",@(number.floatValue)];
                    model.TYPE = [[dic objectForKey:@"TYPE"] integerValue];
                    model.created = [dic objectForKey:@"created"];
                    model.numberOrder = [dic objectForKey:@"numberOrder"];
                    model.storageTime = [dic objectForKey:@"storageTime"];
                    [weakSelf.modelArr addObject:model];
                }
                [weakSelf.tableView reloadData];
                
            }else if ([[obj objectForKey:@"code"] intValue] == 401 || [[obj objectForKey:@"code"] intValue] == 402){
                UIStoryboard *mainStory = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
                [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"passWord"];
                //storyboard里的ID
                XMRegisterViewController *vc = [mainStory instantiateInitialViewController];
                vc.navigationController.navigationBarHidden=NO;
                //                    //设置当前窗口的根控制器
                [UIApplication sharedApplication].keyWindow.rootViewController=vc;
                
                [SVProgressHUD showInfoWithStatus:[obj objectForKey:@"message"]];
                [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
                [SVProgressHUD setDefaultAnimationType:SVProgressHUDAnimationTypeFlat];
                
            }else{
                
                weakSelf.hud=[WKProgressHUD popMessage:[obj objectForKey:@"message"] inView:self.view duration:1 animated:YES];
            }
            
            
        }
        
        [weakSelf UIloadView];
    }];
    
}

//上拉加载更多
- (void)loadMoreShopss{
    
    __weak typeof(self) weakSelf = self;
    self.pageNum++;
    int user = [[[NSUserDefaults standardUserDefaults] objectForKey:@"userId"] intValue];
    NSDictionary * params = @{@"pageNum" : @(self.pageNum),
                              @"pageSize" : @(self.pageSize),
                              @"type" : @(self.shouYiType),
                              @"time" : self.timeStr,
                              @"userId" : @(user),
                              
                              };
    NSLog(@"oj---%@",params);
    [GPosAPI requestViewIncomeOrderListWithParams:params andCallback:^(id obj) {
        NSLog(@"储存列表---%@",obj);
        
        if (obj==nil) {
            weakSelf.hud=[WKProgressHUD popMessage:@"请求失败" inView:self.view duration:1 animated:YES];
            [weakSelf.tableView.mj_footer endRefreshing];
        }else{
            
            if ([[obj objectForKey:@"code"] intValue] == 200) {
                NSArray * arr = [[NSArray alloc] init];
                arr = [obj objectForKey:@"data"];
                for (NSDictionary * dic in arr) {
                    storageModel *model = [[storageModel alloc] init];
                    NSDecimalNumber * number = [dic objectForKey:@"amount"];
                    model.amount = [NSString stringWithFormat:@"%@",@(number.floatValue)];
                    model.TYPE = [[dic objectForKey:@"TYPE"] integerValue];
                    model.created = [dic objectForKey:@"created"];
                    model.numberOrder = [dic objectForKey:@"numberOrder"];
                    model.storageTime = [dic objectForKey:@"storageTime"];
                    [weakSelf.modelArr addObject:model];
                }
                [weakSelf.tableView reloadData];
                [weakSelf.tableView.mj_footer endRefreshing];
                
            }else if ([[obj objectForKey:@"code"] intValue] == 401 || [[obj objectForKey:@"code"] intValue] == 402){
                UIStoryboard *mainStory = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
                [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"passWord"];
                //storyboard里的ID
                XMRegisterViewController *vc = [mainStory instantiateInitialViewController];
                vc.navigationController.navigationBarHidden=NO;
                //                    //设置当前窗口的根控制器
                [UIApplication sharedApplication].keyWindow.rootViewController=vc;
                
                [SVProgressHUD showInfoWithStatus:[obj objectForKey:@"message"]];
                [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
                [SVProgressHUD setDefaultAnimationType:SVProgressHUDAnimationTypeFlat];
                
            }else{
                
                weakSelf.hud=[WKProgressHUD popMessage:[obj objectForKey:@"message"] inView:self.view duration:1 animated:YES];
            }
            
            
        }
        
//        [weakSelf UIloadView];
    }];
    
}

- (void)UIloadView{

    self.leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.leftButton setImage:[UIImage imageNamed:@"icon_rili"] forState:UIControlStateNormal];
    [self.leftButton addTarget:self action:@selector(leftAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.leftButton];
    [self.leftButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).with.offset(kNavbarHeight+10);
        make.left.equalTo(self.view).with.offset(15);
    }];
    
    self.rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.rightButton setTitle:@"类型" forState:UIControlStateNormal];
    self.rightButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [self.rightButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [self.rightButton addTarget:self action:@selector(rightAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.rightButton];
    [self.rightButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.leftButton);
        make.right.equalTo(self.view).with.offset(-15);
    }];
    
    self.tableView = [[UITableView alloc] init];
    self.tableView.backgroundColor = [UIColor colorWithRed:244/255.0f green:244/255.0f blue:244/255.0f alpha:1];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.mj_footer=[MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreShopss)];
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.leftButton.mas_bottom).with.offset(10);
        make.left.equalTo(self.view).with.offset(0);
        make.right.equalTo(self.view).with.offset(0);
        make.bottom.equalTo(self.view).with.offset(-kBottomSafeHeight);
    }];
    
    
}

//选择日期
- (void)leftAction:(UIButton *)sedner {
    
    DateTimePickerView *pickerView = [[DateTimePickerView alloc] init];
    self.datePickerView = pickerView;
    pickerView.delegate = self;
    pickerView.pickerViewMode = DatePickerViewDateMode;
    [self.view addSubview:pickerView];
    [pickerView showDateTimePickerView];
    
}

#pragma mark - delegate

- (void)didClickFinishDateTimePickerView:(NSString *)date{
    
     NSString *strUrl = [date stringByReplacingOccurrencesOfString:@"-" withString:@""];
//    self.textL.text = date
    self.timeStr = strUrl;
    NSLog(@"shijian---%@",strUrl);
    [self loadData];
}

//选择类型
- (void)rightAction:(UIButton *)sender {
    [PopupView addCellWithIcon:nil text:@"个人" action:^{
        self.shouYiType = 1;
        [self loadData];
        NSLog(@"点第一个");
    }];
    [PopupView addCellWithIcon:nil text:@"推广" action:^{
        self.shouYiType = 2;
        [self loadData];
        NSLog(@"点第二个");
    }];
     [PopupView popupViewInButton:sender];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.modelArr.count;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{//rankingCell
    
    
    earningsViewCell * cell = [[earningsViewCell alloc] init];
    
    cell = [tableView dequeueReusableCellWithIdentifier:@"earningsCell"];
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"earningsViewCell" owner:self options:nil] firstObject];
    }
    cell.topView.layer.cornerRadius = 5;
    cell.contenView.layer.cornerRadius = 5;
    if ([self.modelArr[indexPath.row] TYPE] == 1) {
        cell.shoyiImage.image = [UIImage imageNamed:@"icon_gerensy"];
        cell.typeLabel.text = @"个人";
    }else if ([self.modelArr[indexPath.row] TYPE] == 2){
        cell.shoyiImage.image = [UIImage imageNamed:@"icon_tgsy"];
        cell.typeLabel.text = @"推广";
    }
    cell.orderNumLabel.text =[NSString stringWithFormat:@"订单号:%@",[self.modelArr[indexPath.row] numberOrder]];
    cell.shouYiLabel.text = [NSString stringWithFormat:@"收益: %@GPOS",[self.modelArr[indexPath.row] amount]];
    
    // timeStampString 是服务器返回的13位时间戳
    NSString *timeStampString  = [self.modelArr[indexPath.row] created];
    NSString * storageTimeStr =[self.modelArr[indexPath.row] storageTime];
    
    // iOS 生成的时间戳是10位
    NSTimeInterval interval=[timeStampString doubleValue] / 1000.0;
    NSDate *date  = [NSDate dateWithTimeIntervalSince1970:interval];
    
    NSTimeInterval intervalOne=[storageTimeStr doubleValue] / 1000.0;
    NSDate *dateOne  = [NSDate dateWithTimeIntervalSince1970:intervalOne];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSDateFormatter *formatterOne = [[NSDateFormatter alloc] init];
    [formatterOne setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSString *dateString    = [formatter stringFromDate: date];
    NSString *dateStringOne    = [formatterOne stringFromDate: dateOne];
    cell.chuCunTimeLabel.text = [NSString stringWithFormat:@"储存时间：%@",dateStringOne];
    cell.chuangJianTimeLabel.text = [NSString stringWithFormat:@"创建时间：%@",dateString];
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 140;
}
@end
